package com.ruoyi.weixin.aspect;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.weixin.anno.ILog;
import com.ruoyi.weixin.entity.TLog;
import com.ruoyi.weixin.entity.User;
import com.ruoyi.weixin.service.TLogService;
import com.ruoyi.weixin.service.UserService;
import com.ruoyi.weixin.untils.BaseContext;
import com.ruoyi.weixin.untils.JWTUtils;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @Author FengZeng
 * @Date 2022-05-21 00:42
 * @Description TODO
 */
@Aspect
@Component
@RequiredArgsConstructor
public class LogAspects {

  @Autowired
  RedisCache redisCache;

  @Autowired
  UserService userService;


  private final TLogService logService;

  @Pointcut("@annotation(com.ruoyi.weixin.anno.ILog)")
  public void pointcut() {
  }
  @Around("pointcut()")
  public Object around(ProceedingJoinPoint point) {
    Object result = null;
    long beginTime = System.currentTimeMillis();
    try {
      result = point.proceed();
    } catch (Throwable e) {
      e.printStackTrace();
    }
    long costTime = System.currentTimeMillis() - beginTime;
    saveLog(point, costTime);
    return result;
  }
  private void saveLog(ProceedingJoinPoint point, long costTime) {
    // 通过 point 拿到方法签名
    MethodSignature methodSignature = (MethodSignature) point.getSignature();
    // 通过方法签名拿到被调用的方法
    Method method = methodSignature.getMethod();
    TLog log = new TLog();
    // 通过方法区获取方法上的 ILog 注解
    ILog logAnnotation = method.getAnnotation(ILog.class);
    if (logAnnotation != null) {
      log.setOperation(logAnnotation.value());
    }
    String className = point.getTarget().getClass().getName();
    String methodName = methodSignature.getName();
    log.setMethod(className + "." + methodName + "()");
    // 获取方法的参数
    Object[] args = point.getArgs();
    LocalVariableTableParameterNameDiscoverer l = new LocalVariableTableParameterNameDiscoverer();
    String[] parameterNames = l.getParameterNames(method);
    if (args != null && parameterNames != null) {
      StringBuilder param = new StringBuilder();
      for (int i = 0; i < args.length; i++) {
        param.append(" ").append(parameterNames[i]).append(":").append(args[i]);
      }
      log.setParams(param.toString());
    }
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

    HttpServletRequest request = attributes.getRequest();
    String ip = request.getRemoteAddr();
    log.setIp(ip);

    String token = request.getHeader("token");
    String id = JWTUtils.validateToken(token);
    User user = userService.getById(id);

    log.setUserId(user.getId());
    log.setNickName(user.getNickName());
    log.setRealName(user.getRealName());

    log.setCostTime(costTime);
    log.setCreateTime(LocalDateTime.now());
    logService.save(log);
  }
}
